package com.dqp.cslggroup.Api;

import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.ConnectSever.SeverIP;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.Result;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.StringUtil;
import com.dqp.cslggroup.Util.UserAgent;
import com.dqp.cslggroup.bean.Score;
import com.dqp.cslggroup.bean.course;
import com.dqp.cslggroup.greendao.courseDao;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.Map;

public class jwxtApi {
    private static Connection.Response response;
    static String ip = SharedPreferencesUtil.getIp(MyApplication.getContext());

    /*
     * @Description: 教务系统登录
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/1
     */
    public static JSONObject login(Map<String, String> cookies, String sno, String password, String remberMe) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            Connection.Response response = Jsoup.connect(ip + "/cslg/jwxt/login")
                    .ignoreContentType(true)
                    .method(Connection.Method.POST)
                    .data("password", password)
                    .data("sno", sno)
                    .data("remberMe", remberMe)
                    .data("vpn", "1")
                    .userAgent(UserAgent.userAgent)
                    .cookies(cookies)
                    .timeout(60000)
                    .followRedirects(true)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("返回数据异常！");
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("登录异常");
        }
    }

    /*
     * @Description: 获取学生信息
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    public static JSONObject info(String sno, Map<String, String> cookies) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            Connection.Response response = Jsoup.connect(ip + "/cslg/jwxt/info")
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .data("sno", sno)
                    .cookies(cookies)
                    .timeout(60000)
                    .followRedirects(true)
                    .execute();
            Log.e("info", response.body());
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("异常");
        }

    }

    /*
     * @Description: 获取课程
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    public static JSONObject course(String sno, int year, int term, Map<String, String> cookies) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            if (StringUtil.isEmpty(sno, 9) || cookies == null) return Result.error("参数不合法");
            Connection.Response response = Jsoup.connect(ip + "/cslg/jwxt/getCourse")
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .data("sno", sno)
                    .data("year", year + "")
                    .data("term", term + "")
                    .cookies(cookies)
                    .timeout(60000)
                    .followRedirects(true)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (Result.jsonResultIsTure(jsonObject))
                parseCourse(jsonObject, sno);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("登录异常");
        }
    }

    /*
     * @Description: 转换课表
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    private static void parseCourse(JSONObject jsonObject, String sno) {
        if (jsonObject != null && jsonObject.containsKey("courseList")) {
            MyApplication.getDaoInstant().getCourseDao().queryBuilder().where(courseDao.Properties.Who.eq(0)).buildDelete().executeDeleteWithoutDetachingEntities();
            JSONArray timeTable = JSON.parseArray(jsonObject.getString("courseList"));
            for (Object o : timeTable) {
                JSONObject lesson = (JSONObject) o;
                course c = new course();
                c.setSno(sno);
                c.setXqjmc(lesson.getString("xqjmc"));
                c.setKcmc(lesson.getString("kcmc"));
                c.setXm(lesson.getString("xm"));
                c.setXqmc(lesson.getString("xqmc"));
                c.setCdmc(lesson.getString("cdmc"));
                c.setZcd(lesson.getString("zcd"));
                c.setXf(lesson.getString("xf"));
                c.setKhfsmc(lesson.getString("khfsmc"));
                c.setXnm(lesson.getString("xnm"));
                c.setXqj(lesson.getIntValue("xqj"));
                c.setKcxszc(lesson.getString("kcxszc"));
                c.setJc(lesson.getString("jc"));
                c.setXqm(lesson.getString("xqm"));
                c.setKclb(lesson.getString("kclb"));
                c.setWho(0);
                c.setWeeklist(lesson.getString("weeklist"));
                MyApplication.getDaoInstant().getCourseDao().insert(c);
            }
        }
    }


    /*
     * @Description: 获取成绩
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    public static JSONObject getGrades(String sno, int year, int term, Map<String, String> cookies) {
        if (StringUtil.isEmpty(sno, 9) || cookies == null) return Result.error("参数不合法");
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            response = Jsoup.connect(ip + "/cslg/jwxt/searchGrade")
                    .data("sno", sno)
                    .data("year", year + "")
                    .data("term", term + "")
                    .cookies(cookies)
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(60000)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (Result.jsonResultIsTure(jsonObject))
                parseScore(jsonObject, sno);
            return jsonObject;
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("登录异常");
        }

    }

    private static void parseScore(JSONObject jsonObject, String sno) {
        if (jsonObject == null || !jsonObject.containsKey("details")) return;
//            MyApplication.getDaoInstant().getCourseDao().queryBuilder().where(courseDao.Properties.Who.eq(0)).buildDelete().executeDeleteWithoutDetachingEntities();
        jsonObject = jsonObject.getJSONObject("details");
        if (!jsonObject.containsKey("score")) return;
        String jsonObjectString = jsonObject.getString("score");
        JSONArray array = JSONArray.parseArray(jsonObjectString);
        for (Object o : array) {
            JSONObject lesson = (JSONObject) o;
            Score score = new Score();
            score.setCname(lesson.getString("kcmc"));
            score.setXf(lesson.getString("xf"));
            score.setGrade(lesson.getString("bfzcj"));
            score.setJd(lesson.getString("jd"));
            score.setJxb_id(lesson.getString("jxb_id"));
            score.setXnm(lesson.getString("xnm"));
            score.setXqm(lesson.getString("xqm"));
            score.setSno(sno);
//            if (lesson.containsKey("scoreDetails")) {
//                JSONArray array1 = JSON.parseArray(lesson.getString("scoreDetails"));
//                List<scoreDetails> list = new ArrayList<>();
//                for (Object o1 : array1) {
//                    JSONObject details = (JSONObject) o1;
//                    scoreDetails scoreDetails = details.toJavaObject(com.dqp.cslggroup.bean.scoreDetails.class);
//                    list.add(scoreDetails);
//                }
//                String detialStr = StringUtil.listToString(list, ',');
//                Log.e("detialStr",detialStr);
//                score.setScoreDetailsList(detialStr);
//            }
            MyApplication.getDaoInstant().getScoreDao().insertOrReplace(score);
        }

    }


    /*
     * @Description: 获取考场
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    public static JSONObject getExam(String sno, String year, String term, Map<String, String> cookies) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            response = Jsoup.connect(ip + "/cslg/jwxt/searchExam")
                    .data("sno", sno)
                    .data("year", year)
                    .data("term", term)
                    .cookies(cookies)
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(60000)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("登录异常");
    }


    public static JSONObject getGradeTest(String sno, Map<String, String> cookies) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            response = Jsoup.connect(ip + "/cslg/jwxt/searchGradeTest")
                    .data("sno", sno)
                    .cookies(cookies)
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(60000)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("登录异常");
    }


    public static JSONObject shareCourse(String sno, String year, String term) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            response = Jsoup.connect(ip + "/cslg/jwxt/shareCourse")
                    .data("sno", sno)
                    .data("year", year)
                    .data("term", term)
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(60000)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("登录异常");
    }

    public static JSONObject getShareCourse(String token) {
        try {
            if (ip == null) ip = SeverIP.getDefvalueUrl();
            response = Jsoup.connect(ip + "/cslg/jwxt/getShareCourse")
                    .data("token", token)
                    .ignoreContentType(true)
                    .method(Connection.Method.GET)
                    .timeout(60000)
                    .execute();
            if (response.body() == null) return Result.error("响应超时！");
            String json = response.body();
            if (!StringUtil.isJson(json)) return Result.error("服务器出小差了！");
            JSONObject jsonObject = JSONObject.parseObject(json);
            if (Result.jsonResultIsTure(jsonObject))
                parseShareCourse(jsonObject);
            return JSONObject.parseObject(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error("登录异常");
    }

    /*
     * @Description: 转换课表
     * @Param:
     * @return:
     * @Author: 董琴平
     * @Date: 2021/9/3
     */
    private static void parseShareCourse(JSONObject jsonObject) {
        if (jsonObject != null && jsonObject.containsKey("courseList")) {
            MyApplication.getDaoInstant().getCourseDao().queryBuilder().where(courseDao.Properties.Who.eq(1)).buildDelete().executeDeleteWithoutDetachingEntities();
            JSONArray timeTable = JSON.parseArray(jsonObject.getString("courseList"));
            for (Object o : timeTable) {
                JSONObject lesson = (JSONObject) o;
                course c = new course();
                c.setSno("000000000");
                c.setXqjmc(lesson.getString("xqjmc"));
                c.setKcmc(lesson.getString("kcmc"));
                c.setXm(lesson.getString("xm"));
                c.setXqmc(lesson.getString("xqmc"));
                c.setCdmc(lesson.getString("cdmc"));
                c.setZcd(lesson.getString("zcd"));
                c.setXf(lesson.getString("xf"));
                c.setKhfsmc(lesson.getString("khfsmc"));
                c.setXnm(lesson.getString("xnm"));
                c.setXqj(lesson.getIntValue("xqj"));
                c.setKcxszc(lesson.getString("kcxszc"));
                c.setJc(lesson.getString("jc"));
                c.setXqm(lesson.getString("xqm"));
                c.setKclb(lesson.getString("kclb"));
                c.setWho(1);
                c.setWeeklist(lesson.getString("weeklist"));
                MyApplication.getDaoInstant().getCourseDao().insertOrReplace(c);
            }
        }
    }


}
